﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.EFDBFirst;
using YiYiTong.Rocket.Model;
using System.ComponentModel;
using YiYiTong.Rocket.Model.Manager;
using YiYiTong.Rocket.Business;
using YiYiTong.Rocket.Model.ParamModel;
using System.Text.RegularExpressions;

namespace YiYiTong.Rocket.ManageWeb.Controllers
{
    public class PushMsgController : BaseController
    {
        [Description("个人消息列表")]
        [ViewPage]
        public ActionResult PushMsgList(PushMsgListQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            //条件筛选
            var queryable = dbcontext.ADZ_Pushmessage.Where(t => t.IsShow == 1);

            if (!string.IsNullOrWhiteSpace(queryModel.MsgTitle))
                queryable = queryable.Where(t => t.MsgTitle.Contains(queryModel.MsgTitle));

            if (queryModel.CreateTime_beg.HasValue)
                queryable = queryable.Where(t => t.CreateTime >= queryModel.CreateTime_beg);
            if (queryModel.CreateTime_end.HasValue)
            {
                var endTime = queryModel.CreateTime_end.Value.AddSeconds(1);
                queryable = queryable.Where(t => t.CreateTime < endTime);
            }

            int rowcounts = queryable.Count();

            ViewData["AllCount"] = rowcounts;

            var querylist = queryable.OrderByDescending(t => t.ID)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            PagedList<ADZ_Pushmessage> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<ADZ_Pushmessage>(querylist, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }


        [Description("添加修改推送消息")]
        [ViewPage]
        public ActionResult addPushMsg(long id = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            AddPushMsgModel paramModel = new AddPushMsgModel();
            if (id > 0)
            {
                var ADZ_Pushmessage = dbcontext.ADZ_Pushmessage.FirstOrDefault(t => t.ID == id);
                if (ADZ_Pushmessage != null)
                {
                    paramModel.aDZ_Pushmessage = ADZ_Pushmessage;
                    ViewBag.ParamModel = paramModel;
                }
                ViewBag.Title = "修改记录";
            }
            else
                ViewBag.Title = "添加记录";

            return View(paramModel);
        }

        [Description("添加修改推送消息")]
        [HttpPost]
        public ActionResult addPushMsg(AddPushMsgModel paramModel)
        {
            Utils.Trim(paramModel);
            long id = paramModel.aDZ_Pushmessage.ID;
            ResponseMsg resMsg = new ResponseMsg();
            if (!ModelState.IsValid)
            {
                resMsg.IsSuccess = false;
                resMsg.Message = ModelState.Values.First().Errors[0].ErrorMessage;
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            paramModel = paramModel ?? new AddPushMsgModel();
            ViewBag.ParamModel = paramModel;

            paramModel.aDZ_Pushmessage.MsgType = 1;
            paramModel.aDZ_Pushmessage.ReceiveType = 0;
            paramModel.aDZ_Pushmessage.Sender = new CurrentUser().user.uid.ToString();
            var result = PushMsgBiz.Instance.AddPushMsg(paramModel);

            resMsg.IsSuccess = result.Item1;
            resMsg.Message = result.Item2;
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }


        [Description("删除推送消息")]
        [HttpPost]
        public ActionResult DeletePushMsg(long id = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            AddPushMsgModel paramModel = new AddPushMsgModel();
            if (id > 0)
            {
                var aDZ_Pushmessage = dbcontext.ADZ_Pushmessage.FirstOrDefault(t => t.ID == id && t.IsShow == 1);
                if (aDZ_Pushmessage != null)
                {
                    aDZ_Pushmessage.IsShow = 0;
                    dbcontext.SaveChanges();
                }
            }
            resMsg.IsSuccess = true;
            resMsg.Message = "操作成功";
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 消息推送
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult PushMsg(long id = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            if (id > 0)
            {
                var aDZ_Pushmessage = dbcontext.ADZ_Pushmessage.FirstOrDefault(t => t.ID == id && t.IsShow == 1);
                if (aDZ_Pushmessage != null)
                {
                    PushMessageRequest request = PushMsgBiz.Instance.GetPushMsgReq(dbcontext, aDZ_Pushmessage);
                    if (request != null)
                    {
                        if (JpushBiz.PushMsg(request))
                        {
                            //推送成功，更新相关信息
                            aDZ_Pushmessage.PushTime = DateTime.Now;
                            aDZ_Pushmessage.MsgStatus = 10;
                            dbcontext.SaveChanges();

                            resMsg.IsSuccess = true;
                            resMsg.Message = "操作成功";
                        }
                        else
                            resMsg.Message = "推送失败";
                    }
                    else
                    {
                        LogHelper.Error(string.Format("针对用户推送消息失败，推送内容：{0} 原因：用户未绑定设备", aDZ_Pushmessage.MsgText));
                        resMsg.IsSuccess = false;
                        resMsg.Message = "推送失败，用户未绑定设备";
                        return Json(resMsg, JsonRequestBehavior.AllowGet);
                    }
                }
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 批量消息推送
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult ToMorePushMsg(string ids)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";
            if (!string.IsNullOrEmpty(ids))
            {
                if (ids.EndsWith(","))
                    ids = ids.Substring(0, ids.Length - 1);

                bool is_push = false;
                var id_arr = StringHelper.Split(ids, ',');
                ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
                foreach (var item in id_arr)
                {
                    long id = ConvertHelper.TryPraseInt(item, 0);
                    if (id > 0)
                    {
                        var aDZ_Pushmessage = dbcontext.ADZ_Pushmessage.FirstOrDefault(t => t.ID == id && t.IsShow == 1);
                        if (aDZ_Pushmessage != null)
                        {
                            PushMessageRequest request = PushMsgBiz.Instance.GetPushMsgReq(dbcontext, aDZ_Pushmessage);
                            if (request != null)
                            {
                                if (JpushBiz.PushMsg(request))
                                {
                                    //推送成功，更新相关信息
                                    aDZ_Pushmessage.PushTime = DateTime.Now;
                                    aDZ_Pushmessage.MsgStatus = 10;
                                    dbcontext.SaveChanges();
                                    is_push = true;
                                }
                                else
                                    is_push = false;
                            }

                        }
                    }
                }

                if (is_push)
                {
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                }
                else
                    resMsg.Message = "推送失败";
            }
            else
                resMsg.Message = "请选择要批量推送的消息";
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }
    }
}